// pages/due-detail/due-detail.js
import Dialog from 'tdesign-miniprogram/dialog/index';
import {
  imgFormat
} from '../../utils/imgFormat'
import axios from '../../utils/axios';
import dayjs from 'dayjs';

const formatTime = 'YYYY-MM-DD HH:mm';
const threeSeconds = 3 * 1000;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderDetail: {},
    timePeriod: '',
    duration: 0,
    amount: 0,
    item: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options = {}) {
    this.openid = wx.getStorageSync('openid');
    if (options.orderId || options.ID) {
      this.setData({
        orderId: options.orderId || options.ID
      });

      this.getOrderDetail(this.data.orderId);

      this.orderDetailTimer = setInterval(() => {
        this.getOrderDetail(options.orderId);
      }, threeSeconds);


    } else {
      wx.switchTab({
        url: '/pages/due/due',
      });
    }
    // else if (options && options.item) {
    //   let item = JSON.parse(options.item)
    //   const timePeriod = `${dayjs(item.startTime).format(formatTime)} - ${dayjs(item.endTime).format(
    //     'HH:mm',
    //   )}`;
    //   item.banners = imgFormat(item.roomDetail.banners)
    //   console.log(item)
    //   this.setData({
    //     item: item,
    //     timePeriod
    //   })
    // } 
  },

  onUnload() {
    if (this.orderDetailTimer) {
      clearInterval(this.orderDetailTimer);
    }
  },

  async getOrderDetail(orderId) {
    if (!orderId) {
      return
    }
    const res = await axios.get(`/app/orderList?wxId=${this.openid}&ID=${orderId}`);
    const orderDetail = res?.data?.[0];
    const timePeriod = `${dayjs(orderDetail.startTime).format(formatTime)} - ${dayjs(orderDetail.endTime).format(
      'HH:mm',
    )}`;
    const duration = dayjs(orderDetail.endTime).diff(dayjs(orderDetail.startTime), 'hour');
    const amount = duration * orderDetail.price;
    const item = orderDetail.roomDetail;
    item.banners = imgFormat(item.banners);
    if(item.wifi){
      item.wifi1 = item.wifi.split("-")[0];
      item.wifi2 = item.wifi.split("-")[1];
    }
    this.getCmsInfo(item.company_id);
    this.setData({
      orderDetail: {
        ...orderDetail
      },
      timePeriod,
      duration,
      amount,
      item
    });
    if (orderDetail.status !== 1) {
      clearInterval(this.orderDetailTimer);
    }
  },

  cancel() {
    const dialogConfig = {
      context: this,
      title: '取消预定',
      content: '您确认取消当前的预订吗，取消后费用将原路退回',
      confirmBtn: '确定',
      cancelBtn: '取消',
    };

    Dialog.confirm(dialogConfig)
      .then(() => {
        axios.post('/app/cancelOrder', {
          id: +this.data.orderId
        }).then((res) => {
          if (res.data === 'success') {
            Dialog.close();
            wx.showToast({
              title: '取消订单成功',
              icon: 'success'
            })
            this.getOrderDetail(this.data.orderId);
          }
        });
      })
      .catch(() => console.log('点击了取消'))
      .finally(() => {
        Dialog.close()
      });
  },
  userSubmit() {},
  extendTime() {
    const roomId = this.data.item.ID;
    const orderId = this.data.orderId;
    wx.redirectTo({
      url: './addDuration/index?roomId='+roomId +"&orderId="+orderId,
    })
  },
  call() {
    let phoneNumber = "15600595555";
    if(this.data.cmsInfo?.phone_list?.[0]?.phone){
      phoneNumber = this.data.cmsInfo.phone_list[0].phone
    }
    wx.makePhoneCall({
      phoneNumber,
    })
  },
  getCmsInfo(id){
    axios.get("/app/dpList?id="+id).then(res=>{
      this.setData({
        cmsInfo:res.data[0]
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // wx.switchTab({
    //   url: '/pages/due/due',
    // })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});